from pyparsing_py3 import *

class ResParser:
	def __init__(self):
		self.parser = self.build_parser()

	def build_parser(self):
		stringchars = alphanums + ".,/\\=-*!@#$%^&*_"
		quotedString = dblQuotedString.setParseAction(removeQuotes)
		string = (quotedString | Word(stringchars))
		endl = Suppress((dblSlashComment + LineEnd()) | LineEnd())
		
		name = string("name")
		context = (Suppress('[') + Word(stringchars) + Suppress(']'))("context")
		statement = Group(string("key") + string("value") +	((context + endl) | endl))("stmt")
		braced_block = Forward()
		braced_block << (name + Optional(context) + Suppress('{') +\
						 ZeroOrMore(dblSlashComment | braced_block | statement) +\
						 Suppress('}'))("block")
		return ZeroOrMore(braced_block | dblSlashComment)

	def parse_file(self, fname):
		with open(fname, 'r') as f:
			fstr = f.read()
			return self.parse_str(fstr)
	
	def parse_str(self, str):
		return self.parser.parseString(str)
	
if __name__ == '__main__':
	import pprint; p = pprint.pprint
	r = ResParser()
	p(r.parse_file('../tf/scripts/hudlayout.res').asList())
